package com.enlorenz.core.channel.activemq;

import com.enlorenz.core.base.IReqResMessageHandle;
import com.enlorenz.core.channel.IChannelEngine;
import com.enlorenz.core.engine.AbstractEngine;
import com.enlorenz.core.queue.transfer.imp.WaitMessageQueue;

/**
 * 双通道的MQ
 * 带MQ发送通道和MQ接收通道
 * 从接收通道接收数据然后转发到发送通道
 * @author lcb
 */
public class MQSendRecvChannel<T> extends AbstractEngine implements IReqResMessageHandle<T>,IChannelEngine{
	//客户端MQ通道
	private MQClientChannel clientChannel=new MQClientChannel();
	//服务端MQ通道
	private MQServerChannel serverChannel=new MQServerChannel();
	//客户端MQ URL
	private String clientMqUrl;
	//客户端MQ对列名
	private String clientMqName;
	
	//服务端MQ URL
	private String serverMqUrl;
	//服务端MQ对列名
	private String serverMqName;
	//发送队列
	private WaitMessageQueue<T> sendQueue=new WaitMessageQueue<T>();
	//接收队列
	private WaitMessageQueue<T> recvQueue=new WaitMessageQueue<T>();
	
	public void setClientMqUrl(String clientMqUrl) {
		this.clientMqUrl = clientMqUrl;
	}

	public void setClientMqName(String clientMqName) {
		this.clientMqName = clientMqName;
	}

	public void setServerMqUrl(String serverMqUrl) {
		this.serverMqUrl = serverMqUrl;
	}

	public void setServerMqName(String serverMqName) {
		this.serverMqName = serverMqName;
	}


	@Override
	protected void initEngine() throws Exception {
		clientChannel.setName(this.getName()+"2"+clientMqName);
		clientChannel.setMqName(clientMqName);
		clientChannel.setMqUrl(clientMqUrl);
		clientChannel.setWaitMessageQueue(sendQueue);
		clientChannel.init();
		
		serverChannel.setName(clientMqName+"2"+this.getName());
		serverChannel.setMqName(serverMqName);
		serverChannel.setMqUrl(serverMqUrl);
		serverChannel.setRecvQueue(recvQueue);
		serverChannel.init();
	}
	
	@Override
	public boolean isAlive() {
		if(!clientChannel.isAlive()){
			return clientChannel.isAlive();
		}
		
		if(!serverChannel.isAlive()){
			return serverChannel.isAlive();
		}
		
		return true;
	}

	

	@Override
	protected void startEngine() throws Exception {
		serverChannel.start();
		clientChannel.start();
	}

	@Override
	protected void shutdownEngine() throws Exception {
		serverChannel.shutdown();
		clientChannel.shutdown();
	}


	@Override
	public T reqResMsgHandle(T message){
		sendQueue.addMsg(message);
		return recvQueue.getMsg();
	}
	
	
}
